package com.yimi.yinhepda.utils.spinner;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.pda.ym.utils.SpinnerData;
import com.yimi.yinhepda.R;
import com.pda.ym.utils.StringHelper;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author elegant
 * @date 20140529
 */
public class SpinnerWithCodeAdapter extends BaseAdapter implements OnItemSelectedListener {

  private Context context;
  private Spinner spinner;
  private List<SpinnerData> optionList;
  private HashMap<Integer, Boolean> isSelected;
  private Map optionMap = null;

  /** 是否有特殊操作 */
  private boolean haveSpecial;
  private Class className;
  private String methodName;

  /**
   * 需要放置Spinner选择的值的隐藏控件,为了方便系统在Activity里面的统一处理，此处建议使用**HiddenTag
   * 如果不设置hidden对象，则需要在调研那个SpinnerUtil的Activity里面，手动的调用getSelectedValue方法获取选中的值
   */
  private TextView spinnerHidden;

  public SpinnerWithCodeAdapter(Context context, List<SpinnerData> optionList, Spinner spinner) {
    this.context = context;
    this.spinner = spinner;
    this.optionList = optionList;
    isSelected = new HashMap<Integer, Boolean>();
    if (optionList != null) {
      for (int i = 0; i < optionList.size(); i++) {
        getIsSelected().put(i, false);
      }
    }
    this.spinner.setAdapter(this);
    this.spinner.setOnItemSelectedListener(this);
  }

  @Override public int getCount() {
    return optionList.size();
  }

  @Override public String getItem(int position) {
    SpinnerData option = this.getSelectedOption(position);
    if (option != null) {
      return option.getText();
    } else {
      return "";
    }
  }

  @Override public long getItemId(int position) {
    return position;
  }

  public String getSelectedOptionCode(int position) {
    SpinnerData option = this.getSelectedOption(position);
    if (option != null) {
      return option.getValue();
    } else {
      return "";
    }
  }

  public String getSelectedOptionCode() {

    SpinnerData option = this.getSelectedOption();
    if (option != null) {
      return option.getValue();
    } else {
      return "";
    }
  }

  public String getSelectedOptionLabel(int position) {
    SpinnerData option = this.getSelectedOption(position);
    if (option != null) {
      return option.getText();
    } else {
      return "";
    }
  }

  public String getSelectedOptionLabel() {

    SpinnerData option = this.getSelectedOption();
    if (option != null) {
      return option.getText();
    } else {
      return "";
    }
  }

  public SpinnerData getSelectedOption() {
    int position = this.spinner.getSelectedItemPosition();
    return getSelectedOption(position);
  }

  public SpinnerData getSelectedOption(int position) {
    SpinnerData option = null;
    try {
      option = optionList.get(position);
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    return option;
  }

  ViewHolder holder;

  @Override public View getView(int position, View convertView, ViewGroup parent) {
    final String item = getItem(position);
    if (convertView == null) {
      LayoutInflater li = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
      convertView = li.inflate(R.layout.list_item_spinner, parent, false);
      holder = new ViewHolder();
      holder.layout = (LinearLayout) convertView.findViewById(R.id.layout);
      holder.text = (TextView) convertView.findViewById(R.id.text);

      convertView.setTag(holder);
    } else {
      holder = (ViewHolder) convertView.getTag();
    }

    holder.layout.setBackgroundColor(context.getResources().getColor(R.color.white));
    if (getIsSelected().get(position)) {
      holder.layout.setBackgroundColor(context.getResources().getColor(R.color.login_backline_color));
    }

    holder.text.setText(item);

    return convertView;
  }

  static class ViewHolder {
    LinearLayout layout;
    TextView text;
  }

  public HashMap<Integer, Boolean> getIsSelected() {
    return isSelected;
  }

  public void setSelect(int position) {
    for (int i = 0; i < optionList.size(); i++) {
      getIsSelected().put(i, false);
    }
    getIsSelected().put(position, true);
  }

  @Override public void onItemSelected(AdapterView<?> adapter, View item, int position, long id) {
    setSelect(position);

    SpinnerData selectedItem = this.getSelectedOption(position);
    if (spinnerHidden != null && selectedItem != null) {
      spinnerHidden.setText(selectedItem.getValue());
    }
    if (haveSpecial) {
      this.specialMethod(selectedItem);
    }
  }

  @Override public void onNothingSelected(AdapterView<?> arg0) {
    // TODO Auto-generated method stub

  }

  /**
   * 列表选择要执行的特殊操作
   *
   * @note 要调用的方法必须有个参数SpinnerData
   */
  private void specialMethod(SpinnerData item) {
    if (!StringHelper.isEmpty(methodName) && className != null) {
      try {
        Method runMethod = className.getMethod(methodName, item.getClass());
        runMethod.invoke(context, item);
      } catch (SecurityException e) {
        // TODO Auto-generated catch block
        StringHelper.println(e);
      } catch (IllegalArgumentException e) {
        // TODO Auto-generated catch block
        StringHelper.println(e);
      } catch (NoSuchMethodException e) {
        // TODO Auto-generated catch block
        StringHelper.println(e);
      } catch (IllegalAccessException e) {
        // TODO Auto-generated catch block
        StringHelper.println(e);
      } catch (InvocationTargetException e) {
        // TODO Auto-generated catch block
        StringHelper.println(e);
      }
    }
  }

  public void invokeSpecial(Context context, String methodName) {
    this.context = context;
    this.className = context.getClass();
    this.methodName = methodName;
    this.haveSpecial = true;
  }

  private void convertListToMap() {
    if (optionList != null && !optionList.isEmpty()) {
      optionMap = new HashMap();
      for (int i = 0; i < optionList.size(); i++) {
        SpinnerData item = this.getSelectedOption(i);
        optionMap.put(item.getValue(), String.valueOf(i));
      }
    }
  }

  /**
   * 根据传递过来的value值设置下拉列表的默认选项值
   */
  public void setSelectedOption(String value) {
    if (!StringHelper.isEmpty(value)) {
      for (int i = 0; i < optionList.size(); i++) {
        SpinnerData data = optionList.get(i);
        if (data.getValue().contains(value)) {
          spinner.setSelection(i);
          break;
        }
      }
    }
  }

  public void setSelectedOptionForCompany(String value) {
    if (!StringHelper.isEmpty(value)) {
      for (int i = 0; i < optionList.size(); i++) {
        SpinnerData data = optionList.get(i);
        if (data.getText().contains(value)) {
          spinner.setSelection(i);
          break;
        }
      }
    } else {
      spinner.setSelection(0);
    }
  }

  /**
   * 根据传递过来的value值设置下拉列表的默认选项值
   */
  public void setSelectedOption(Integer value) {
    if (value != null) {
      String valueStr = value.toString();
      this.setSelectedOption(valueStr);
    }
  }

  /**
   * 根据传递过来的value值设置下拉列表的默认选项值
   */
  public void setSelectedOption(Double value) {
    if (value != null) {
      String valueStr = value.toString();
      this.setSelectedOption(valueStr);
    }
  }

  public TextView getSpinnerHidden() {
    return spinnerHidden;
  }

  public void setSpinnerHidden(TextView spinnerHidden) {
    this.spinnerHidden = spinnerHidden;
  }
}
